/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.pig.pigpen.launch;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.rmi.dgc.VMID;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.pig.impl.util.PropertiesUtil;
import org.apache.pig.pigpen.PigPenActivator;
import org.apache.pig.pigpen.PluginConfiguration;
import org.apache.pig.pigpen.preferences.PreferenceConstants;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.model.ILaunchConfigurationDelegate;
import org.eclipse.jdt.launching.AbstractJavaLaunchConfigurationDelegate;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.IVMRunner;
import org.eclipse.jdt.launching.VMRunnerConfiguration;
import org.eclipse.jface.preference.IPreferenceStore;
import org.osgi.framework.Bundle;

public class PigLaunchConfigurationDelegate extends
        AbstractJavaLaunchConfigurationDelegate implements
        ILaunchConfigurationDelegate {

    public void launch(ILaunchConfiguration configuration, String mode,
            ILaunch launch, IProgressMonitor monitor) throws CoreException {
        // TODO Auto-generated method stub

        String mainType = verifyMainTypeName(configuration);

        if (!".pig".equals(mainType.substring(mainType.length() - 4, mainType
                .length()))) {
            abort("Please give a PigLatin input file!", null, 0);
        }

        IVMInstall ivm = verifyVMInstall(configuration);
        IVMRunner runner = ivm.getVMRunner(mode);

        List<String> classPath = new LinkedList<String>();
        classPath.add(System.getProperty("java.class.path"));
        String pigLocation = getPigLocation();
        if (!"".equals(pigLocation)) {
            classPath.add(pigLocation);
        }

        IPreferenceStore store = PigPenActivator.getDefault()
                .getPreferenceStore();
        String stringList = store.getString(PreferenceConstants.P_PROPERTIES);
        Map<String, String> PrefProperties = PluginConfiguration
                .parseString(stringList);
        String confPath = PrefProperties.get(PreferenceConstants.P_CONFPATH);

        if (confPath == null || confPath.length() == 0) {
            abort(
                    "Please set the variable "
                            + PreferenceConstants.P_CONFPATH
                            + " to point to the directory containing the configuration files in Pig preferences",
                    null, 0);

        }

        classPath.add(confPath);

        String[] ClassPath = null;
        ClassPath = classPath.toArray(ClassPath);

        VMRunnerConfiguration runConfig = new VMRunnerConfiguration(
                "org.apache.pig.Main", ClassPath);

        runConfig
                .setProgramArguments(new String[] { " -x mapreduce ", mainType });

        Properties properties = PropertiesUtil.loadPropertiesFromFile();
        String sshGateway = properties.getProperty("ssh.gateway");

        if (sshGateway != null && !"".equals(sshGateway) /*
                                                          * sshGateway.length()
                                                          * > 0
                                                          */) {
            sshGateway = "-Dssh.gateway=" + sshGateway;
        }

        runConfig.setVMArguments(new String[] { sshGateway });

        runner.run(runConfig, launch, monitor);

    }

    private String getPigLocation() {

        String sep = System.getProperty("path.separator");
        StringBuffer sb = new StringBuffer();

        Bundle plugin = Platform.getBundle("org.apache.pig.pigpen");
        URL url = plugin.getEntry("/lib/pig.jar");
        if (url != null) {
            sb.append(resolvePath(url));
        }

        // also try the plugin installation directory
        url = Platform.getPlugin("org.apache.pig.pigpen").getDescriptor()
                .getInstallURL();
        if (url != null) {
            if (sb.length() > 0)
                sb.append(sep);
            sb.append(resolvePath(url));
        }

        return sb.toString();
    }

    private String resolvePath(URL url) {
        URL resolvedURL = null;
        try {
            resolvedURL = Platform.resolve(url);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file = new File(resolvedURL.getFile());
        String path = file.getAbsolutePath();
        if (path.endsWith("!"))
            path = path.substring(0, path.length() - 1);
        return path;
    }
}
